import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter/services.dart';
import 'package:loxen/dialog/toast.dart';
import 'package:loxen/routes/routes.dart';
import 'package:loxen/utils/config.dart';
import 'package:loxen/utils/save_util.dart';
import 'package:loxen/utils/string_res.dart';
import 'package:loxen/viewmode/search_result_viewmodel.dart';
import 'package:provider/provider.dart';

class SearchWidget extends StatelessWidget {
  final SearchType mType;
  final String hintText;
  final int studyCategory;
  final TextEditingController _controller = TextEditingController();
  final FocusNode _focusNode = FocusNode();
  final ValueNotifier<List<String>> _valueListenable = ValueNotifier([]);

  SearchWidget({Key key, this.mType, this.studyCategory, this.hintText})
      : super(key: key) {
    getValues().then((value) {
      _valueListenable.value = value;
    });
  }

  @override
  Widget build(BuildContext context) {
    return ValueListenableProvider.value(
      value: _valueListenable,
      child: Scaffold(
        appBar: PreferredSize(
          preferredSize: Size(double.infinity, 95.h),
          child: Builder(
              builder: (context) => Container(
                    color: Colors.white,
                    child: SafeArea(
                      child: Row(
                        children: <Widget>[
                          Expanded(
                            child: Padding(
                              padding: EdgeInsets.only(
                                  left: 36.w, top: 10.h, bottom: 10.h),
                              child: Container(
                                padding: EdgeInsets.only(left: 30.w),
                                height: 60.h,
                                child: TextField(
                                  controller: _controller,
                                  focusNode: _focusNode,
                                  style: TextStyle(
                                      fontSize: 24.sp,
                                      color: Theme.of(context)
                                          .textTheme
                                          .subtitle2
                                          .color),
                                  textInputAction: TextInputAction.search,
                                  autofocus: true,
                                  onEditingComplete: () {
                                    String data = _controller.text.trim();
                                    _focusNode.unfocus();
                                    if (data == '') {
                                      Toast.show(
                                          StringResources
                                              .nei_rong_bu_neng_wei_kong,
                                          context);
                                      return;
                                    }
                                    changeData(data);
                                    Navigator.of(context).pushNamed(
                                        Routes.search_result,
                                        arguments: {
                                          'type': mType,
                                          'data': data,
                                          'studyCategory': studyCategory
                                        });
                                  },
                                  decoration: InputDecoration(
                                      suffixIcon: InkWell(
                                        onTap: () {
                                          String data = _controller.text.trim();
                                          if (data == '') {
                                            Toast.show(
                                                StringResources
                                                    .nei_rong_bu_neng_wei_kong,
                                                context);
                                            return;
                                          }
                                          changeData(data);
                                          Navigator.of(context).pushNamed(
                                              Routes.search_result,
                                              arguments: {
                                                'type': mType,
                                                'data': data,
                                                'studyCategory': studyCategory
                                              });
                                        },
                                        child: Icon(
                                          Icons.search,
                                          color: Color(0xFFBCC0CA),
                                        ),
                                      ),
                                      border: InputBorder.none,
                                      hintText: hintText,
                                      hintStyle: TextStyle(
                                          fontSize: 24.sp,
                                          color: Color(0xFFBCC0CA))),
                                ),
                                decoration: BoxDecoration(
                                  color: Color(0xFFF6F6F7),
                                ),
                              ),
                            ),
                          ),
                          Padding(
                            padding: EdgeInsets.only(left: 27.w, right: 35.w),
                            child: SizedBox(
                              width: 70.w,
                              height: 60.h,
                              child: InkWell(
                                onTap: () {
                                  Navigator.of(context).pop();
                                },
                                child: Center(
                                  child: Text(
                                    StringResources.qu_xiao,
                                    style: TextStyle(fontSize: 32.sp),
                                  ),
                                ),
                              ),
                            ),
                          )
                        ],
                      ),
                    ),
                  )),
        ),
        body: Container(
          padding: EdgeInsets.only(left: 36.w, right: 36.w, top: 70.h),
          child: Column(
            children: <Widget>[
              Row(
                children: <Widget>[
                  Container(
                    width: 5.w,
                    height: 30.h,
                    color: Color(0xff0caccc),
                  ),
                  Padding(
                    padding: EdgeInsets.only(bottom: 5.h, left: 20.w),
                    child: Text(
                      StringResources.li_shi_ji_lu,
                      style: TextStyle(fontSize: 32.sp),
                    ),
                  ),
                  Expanded(child: Text('')),
                  SizedBox(
                    width: 40.w,
                    height: 40.w,
                    child: InkWell(
                      onTap: () {
                        if (SearchType.INSPIRATION == mType) {
                          SharedPreferencesUtil.putData(
                              Constants.SEARCH_INSPIRATION_CACHE, <String>[]);
                        } else if (SearchType.MATERIAL == mType) {
                          SharedPreferencesUtil.putData(
                              Constants.SEARCH_MATERIAL_CACHE, <String>[]);
                        } else if (SearchType.KNOWLEDGE == mType) {
                          SharedPreferencesUtil.putData(
                              Constants.SEARCH_KNOWLEDGE_CACHE, <String>[]);
                        } else if (SearchType.CASE == mType) {
                          SharedPreferencesUtil.putData(
                              Constants.SEARCH_CASE_CACHE, <String>[]);
                        }
                        _valueListenable.value = [];
                      },
                      child: Center(
                        child: Image.asset(
                          "images/trash_can.png",
                          width: 31.w,
                          height: 31.w,
                        ),
                      ),
                    ),
                  )
                ],
              ),
              Builder(
                  builder: (context) => Container(
                        margin: EdgeInsets.only(top: 40.h),
                        width: double.infinity,
                        child: Wrap(
                          spacing: 30.w,
                          runSpacing: 20.h,
                          children:
                              getItems(context, context.watch<List<String>>()),
                        ),
                      ))
            ],
          ),
        ),
      ),
    );
  }

  List<Widget> getItems(BuildContext context, List<String> strs) {
    List<Widget> items = [];
    for (int i = 0; i < strs.length; i++) {
      items.add(Container(
        height: 40.h,
        padding: EdgeInsets.fromLTRB(15.w, 5.h, 15.w, 5.h),
        decoration: BoxDecoration(
          color: Color(0xFFF6F6F7),
          borderRadius: BorderRadius.circular(40.h),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            InkWell(
              onTap: () {
                Navigator.of(context).pushNamed(Routes.search_result,
                    arguments: {
                      'type': mType,
                      'data': strs[i],
                      'studyCategory': studyCategory
                    });
              },
              child: Text(
                strs[i],
                style: TextStyle(fontSize: 24.sp, color: Color(0xffbcc0ca)),
              ),
            ),
            Padding(
              padding: EdgeInsets.only(left: 17.w),
              child: SizedBox(
                width: 25.w,
                height: 25.w,
                child: InkWell(
                  onTap: () {
                    List<String> list = [];
                    _valueListenable.value.removeAt(i);
                    list.addAll(_valueListenable.value);
                    _valueListenable.value = list;
                    if (mType == SearchType.INSPIRATION) {
                      SharedPreferencesUtil.putData(
                          Constants.SEARCH_INSPIRATION_CACHE, list);
                    } else if (mType == SearchType.MATERIAL) {
                      SharedPreferencesUtil.putData(
                          Constants.SEARCH_MATERIAL_CACHE, list);
                    } else if (mType == SearchType.KNOWLEDGE) {
                      SharedPreferencesUtil.putData(
                          Constants.SEARCH_KNOWLEDGE_CACHE, list);
                    } else if (mType == SearchType.CASE) {
                      SharedPreferencesUtil.putData(
                          Constants.SEARCH_CASE_CACHE, list);
                    }
                  },
                  child: Image.asset(
                    "images/historyDeleteIcon.png",
                    width: 25.w,
                    height: 25.w,
                  ),
                ),
              ),
            )
          ],
        ),
      ));
    }
    return items;
  }

  void changeData(String data) {
    _focusNode.unfocus();
    _controller.text = '';
    if (_valueListenable.value.contains(data)) {
      return;
    }
    List<String> list = [];
    list.addAll(_valueListenable.value);
    list.add(data);
    _valueListenable.value = list;
    if (mType == SearchType.INSPIRATION) {
      SharedPreferencesUtil.putData(Constants.SEARCH_INSPIRATION_CACHE, list);
    } else if (mType == SearchType.MATERIAL) {
      SharedPreferencesUtil.putData(Constants.SEARCH_MATERIAL_CACHE, list);
    } else if (mType == SearchType.KNOWLEDGE) {
      SharedPreferencesUtil.putData(Constants.SEARCH_KNOWLEDGE_CACHE, list);
    } else if (mType == SearchType.CASE) {
      SharedPreferencesUtil.putData(Constants.SEARCH_CASE_CACHE, list);
    }
  }

  Future<List<String>> getValues() async {
    if (SearchType.INSPIRATION == mType) {
      List<dynamic> data = await SharedPreferencesUtil.getData(
          Constants.SEARCH_INSPIRATION_CACHE);
      if (data != null) {
        List<String> list = data.map((e) {
          if (e is String) {
            return e;
          } else {
            return "";
          }
        }).toList();
        return list;
      }
      return <String>[];
    } else if (SearchType.MATERIAL == mType) {
      List<dynamic> data =
          await SharedPreferencesUtil.getData(Constants.SEARCH_MATERIAL_CACHE);
      if (data != null) {
        List<String> list = data.map((e) {
          if (e is String) {
            return e;
          } else {
            return "";
          }
        }).toList();
        return list;
      }
      return <String>[];
    } else if (SearchType.KNOWLEDGE == mType) {
      List<dynamic> data =
          await SharedPreferencesUtil.getData(Constants.SEARCH_KNOWLEDGE_CACHE);
      if (data != null) {
        List<String> list = data.map((e) {
          if (e is String) {
            return e;
          } else {
            return "";
          }
        }).toList();
        return list;
      }
      return <String>[];
    } else if (SearchType.CASE == mType) {
      List<dynamic> data =
          await SharedPreferencesUtil.getData(Constants.SEARCH_CASE_CACHE);
      if (data != null) {
        List<String> list = data.map((e) {
          if (e is String) {
            return e;
          } else {
            return "";
          }
        }).toList();
        return list;
      }
      return <String>[];
    }
    return <String>[];
  }
}
